import requests
import os

# 第一次 Post 请求，获取access_token
def get_access_token():
    # url
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    # 参数
    params = {
        'grant_type': 'client_credentials',    # 固定值
        'client_id': 'EYWyHPbx9jn87mnQqHu2gT1z',
        'client_secret': '08vufcV5AGHyQQubpuOyEWW0SNz44XGM'
    }
    res = requests.post(url, data=params)
    # 请求成功 返回access_token和expires_in
    # 请求失败 返回error和error_description
    res = res.json()
    access_token = res['access_token']
    return access_token
# encoding:utf-8

import requests
import base64

'''
增值税发票识别
'''
# 第二次POST请求
def post_2(file_path):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"
    # 二进制方式打开图片文件
    f = open(file_path, 'rb')
    pdf = base64.b64encode(f.read())
    params = {"pdf_file":pdf}
    access_token = get_access_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    res = response.json()
    return res


def print_to_json(json_name):
    print("发票种类:\t", json_name["words_result"]["InvoiceType"])
    print("发票名称:\t", json_name["words_result"]["InvoiceTypeOrg"])
    print("发票代码:\t", json_name["words_result"]["InvoiceCode"])
    print("发票号码:\t", json_name["words_result"]["InvoiceNum"])
    print("校验码:\t", json_name["words_result"]["CheckCode"])
    print("开票日期:\t", json_name["words_result"]["InvoiceDate"])
    print("购方名称:\t", json_name["words_result"]["PurchaserName"])
    print("购方纳税人识别号:\t", json_name["words_result"]["PurchaserRegisterNum"])
    print("购方地址及电话:\t", json_name["words_result"]["PurchaserAddress"])
    print("购方开户行及帐号:\t", json_name["words_result"]["PurchaserBank"])
    print("销售方名称:\t", json_name["words_result"]["SellerName"])
    print("销售方纳税人识别号:\t", json_name["words_result"]["SellerRegisterNum"])
    print("销售方地址及电话:\t", json_name["words_result"]["SellerAddress"])
    print("销售方开户行及帐号:\t", json_name["words_result"]["SellerBank"])
    print("总计金额:\t", json_name["words_result"]["TotalAmount"])
    print("总计税额:\t", json_name["words_result"]["TotalTax"])
    print("价税合计(大写):\t", json_name["words_result"]["AmountInWords"])
    print("价税合计(小写):\t", json_name["words_result"]["AmountInFiguers"])
    print("密码区:\t", json_name["words_result"]["Password"])
    print("收款人:\t", json_name["words_result"]["Payee"])
    print("复核:\t", json_name["words_result"]["Checker"])
    print("开票人:\t", json_name["words_result"]["NoteDrawer"])
    print("备注:\t", json_name["words_result"]["Remarks"])

# ===写入Excel===

import xlwt
import time

def json_Excel(json_file,i):
    sheet.write(i, 0, json_file["words_result"]["InvoiceType"])
    sheet.write(i, 1, json_file["words_result"]["InvoiceTypeOrg"])
    sheet.write(i, 2, json_file["words_result"]["InvoiceNum"])
    sheet.write(i, 3, json_file["words_result"]["InvoiceDate"])
    sheet.write(i, 4, json_file["words_result"]["PurchaserName"])
    sheet.write(i, 5, json_file["words_result"]["SellerName"])
    sheet.write(i, 6, json_file["words_result"]["TotalAmount"])
    sheet.write(i, 7, json_file["words_result"]["TotalAmount"])
    sheet.write(i, 8, json_file["words_result"]["AmountInFiguers"])
    sheet.write(i, 9, json_file["words_result"]["CommodityTaxRate"][0]["word"])



# ==================================



if __name__ == '__main__':
    root_path = "D:/postdemo/PDF/"
    dirs = os.listdir(root_path)
    ws = xlwt.Workbook()
    sheet = ws.add_sheet(u'发票', cell_overwrite_ok=True)
    sheet.write(0, 0, "发票种类")
    sheet.write(0, 1, "发票名称")
    sheet.write(0, 2, "发票号码")
    sheet.write(0, 3, "开票日期")
    sheet.write(0, 4, "购方名称")
    sheet.write(0, 5, "销售方名称")
    sheet.write(0, 6, "总计金额")
    sheet.write(0, 7, "总计税额")
    sheet.write(0, 8, "价税合计")
    sheet.write(0, 9, "税率")
    i=1
    for file in dirs:
        file_path = root_path + file
        res = post_2(file_path)
        print("正在写入Excel", file)
        json_Excel(res, i)
        if i == 1:
            print_to_json(res)
        i += 1
    now = time.time()
    now1 = time.strftime("%Y%m%d%H%M%S")
    save_path = "D:/postdemo/Excel" + now1
    ws.save('%s_invoice.xls' % save_path)
    print("已保存至Excel文件夹中")